<?php
session_start();
class itemAction extends frontendAction {

    public function _initialize() {
        parent::_initialize();
        // var_dump($this->visitor);exit;
        //访问者控制
        if (!$this->visitor->is_login && in_array(ACTION_NAME, array('jiesuan', 'add_coll', 'add_cars', 'share_item', 'fetch_item', 'publish_item', 'like', 'unlike', 'delete', 'comment'))) {
            IS_AJAX && $this->ajaxReturn(0, L('login_please'));
            $this->redirect('User/login');
        }

        $status_arr = array('待付款', '待发货', '待收货', '交易成功', '交易成功');
        $this->assign('status_arr', $status_arr);
    }

	/*
	 * 添加收藏
	*/
	public function add_coll(){
		$ref = array('status'=>0, 'msg'=>'未知错误');
		$gid = $this->_post('gid', 'intval');
		$goods = $this->_post('goods', 'trim');
		$price = $this->_post('price', 'trim');
		$uid = $this->visitor->info['id'];
		
		$coll = M('collection');
		$goods = M('goods');
		
		$goods_info = $goods->where(array('id'=>$gid))->find();
		if($goods_info){
			$data = array(
				'gid' => $gid,
				'goods' => $goods_info['title'],
				'price' => $goods_info['price'],
				'uid' => $uid
			);
			$ishave = $coll->where($data)->find();
			if($ishave){
				$ref['msg'] = "操作失败,已经收藏过了";
			}else{
				$data['time'] = time();
				$res = $coll->add($data);
				if($res){
					$ref['status'] = 1;
					$ref['msg'] = "操作成功";
				}
			}
		}else{
			
		}
		echo json_encode($ref);
		exit;
	}
	
	/*
	 * 添加购物车
	*/
	public function add_cars(){
		$ref = array('status'=>0, 'msg'=>'未知错误');
		$gid = $this->_post('gid', 'intval');
		$uid = $this->visitor->info['id'];
		
		$item_orders = M('item_orders');
		$goods = M('goods');
		
		$data = array(
			'gid' => $gid,
			'type' => 1,
			'uid' => $uid
		);
		
		$goods_info = $goods->where(array('id'=>$gid))->find();
		if($goods_info){
			$ishave = $item_orders->where($data)->find();
			if($ishave){
				$ref['msg'] = "操作失败,已经加入过购物车了";
			}else{
				$data['goods'] = $goods_info['title'];
				$data['price'] = $goods_info['price'];
				foreach($cate_data = F('cate_data') as $v){
					if($v['id']==$goods_info['cid']){
						$pid = $v['pid'];
						$pid = $pid==0?$v['id']:$pid;
						break;
					}
				}
				foreach($cate_data = F('cate_data') as $v){
					if($v['id']==$pid){
						$data['cate'] = $v['name'];
						break;
					}
				}
				$res = $item_orders->add($data);
				if($res){
					$ref['status'] = 1;
					$ref['msg'] = "操作成功";
				}
			}
		}else{
			$ref['msg'] = "操作失败，没有找到指定的产品";
		}
		echo json_encode($ref);
		exit;
	}
	
    /**
     * 商品详细页
     */
    public function index() {
    	$BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
		$LastDay = date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
		$end_day = date('d', strtotime($LastDay));
		$t = time();
		$s_t = mktime(0,0,0,date('m',$t),1,date('Y',$t));
		$e_t = mktime(23,59,59,date('m',$t),$end_day,date('Y',$t));
		
        $id = $this->_get('id', 'intval');
        !$id && $this->_404();
		
		$goods = M('goods');
		$item_orders = M('item_orders');
		$o_wh = array(
			'gid' => $id,
			'status' => array('egt', 1),
			'support_time' => array('between', "$s_t, $e_t")
		);
		$orderlist = $item_orders->field('sum(num) as sellcount')->where($o_wh)->find();
//        dump($orderlist['sellcount']);exit;
		if($orderlist){
			$this->assign('count', $orderlist['sellcount'] == null ? (0+140) : ($orderlist['sellcount']+140));
		}else{
			$this->assign('count', 0);
		}

		$item = $goods->field('goods.*, cate.unit')->join('wxs_item_cate cate on goods.cid = cate.id')
            ->where(array('goods.id'=>$id))->alias('goods')->find();

		if($item){
			$tmp0 = explode('|',$item['wudu']);
			$tmp1 = array();
			foreach($tmp0 as $v){
				$tmp1[] = array('wd'=>$v);
			}
			$item['wudu'] = $tmp1;
		}
        !$item && $this->_404();
		

        $this->assign('item', $item);

		
		$myimg = false;
        $this->assign('img', $myimg);
        $this->_config_seo(C('pin_seo_config.item'), array(
            'item_title' => $item['title'],
            'item_intro' => $item['intro'],
            'item_tag' => implode(' ', $item['tag_list']),
            'user_name' => $item['uname'],
            'seo_title' => $item['seo_title'],
            'seo_keywords' => $item['seo_keys'],
            'seo_description' => $item['seo_desc'],
        ));
        $this->display();
    }

	/**
	* 确认订单
	*/
	public function jiesuan() {

		$discount = 0.8;

		$uid = $this->visitor->info['id'];
		$id = $this->_get('id', 'trim');
		
		$item_orders = M('item_orders');
		$addr = M('addr');
		$goods = M('goods');
		
		if($_POST){
			$youhuiid = 0;

			$discount_code = $this->_post('discount_code', 'trim');
			if ($discount_code) {
		    	$item =  M("discount")->where(array('code_num'=>$discount_code))->find();
		    	if (empty($item)) {
		    		$ref['status'] = 0;
					$ref['message'] = '无效优惠码\n\r';
					exit(json_encode($ref));
		    	}else{
		    		$discount = $item['discount'];
		    		$youhuiid = $item['id'];
		    	}
			}

			$order_list = true;
			$ojl = $this->_post('ojl', 'trim');
			$jme = M('coupons')->where(array('id'=>$ojl,'status'=>0))->find();
			$yheid = $ojl;
			$yhe = $jme['count'];
			
			$fcar = $this->_post('f', 'trim');
			
			if(substr($fcar, 0, 3)=='car' || substr($fcar, 0, 3)=='odr'){
				if(substr($fcar, 0, 3)=='odr'){
					$order_list = false;
				}
				$fcar = substr($fcar, 3);
			}
			
			$u_addr = $_POST['addr_addr'];
			if(!trim($u_addr)){
				$msg .= "收获地址不能为空\n\r";
			}
			$u_tel = $_POST['addr_tel'];
			if(!trim($u_tel)){
				$msg .= "联系方式不能为空\n\r";
			}
			$u_user = $_POST['addr_user'];
			if(!trim($u_user)){
				$msg .= "收件人不能为空\n\r";
			}
			$i_num = $_POST['item_num'];
			if(trim($i_num)<=0){
				$msg .= "请输入购买数量\n\r";
			}
			$i_price = $_POST['item_price'];
			if(trim($i_price)<=0){
				$msg .= "请勿修改商品单价\n\r";
			}
			$i_id = $_POST['item_id'];
			if(trim($i_id)<=0){
				$msg .= "请勿修改商品ID\n\r";
			}
			
			if($id!=$i_id){
				$msg .= "请确认提供的商品ID是正确的\n\r";
			}else{
				$g = $goods->where(array('id'=>$id))->find();
				if($g){

					if(bccomp($g['price']*$i_num*$discount,$i_price,2) === -1){
						$msg .= "请确认提供的单价是正确的\n\r";
					}else{
						//判断地址库中是否存在新提交的地址
						//$cate
						$pid = 0;
						foreach($cate_data = F('cate_data') as $v){
							if($v['id']==$g['cid']){
								$pid = $v['pid'];
								$pid = $pid==0?$v['id']:$pid;
								break;
							}
						}
						foreach($cate_data = F('cate_data') as $v){
							if($v['id']==$pid){
								$cate = $v['name'];
								break;
							}
						}
						
						$addr_where = array(
							'uid' => $uid,
							'address' => $u_addr,
							'user_name' => $u_user,
							'user_tel' => $u_tel
						);
						$f_addr = $addr->where($addr_where)->find();
						if($f_addr){
							$addr_id = $f_addr['id'];
						}else{
							$addr_id = $addr->add($addr_where);
						}
						$sn = time().rand(1000, 9999);
						//生成订单信息，并写入库表
						$data = array(
							'goods' => $g['title'],
							'price' => $g['price']*$discount,
							'num' => $i_num,
							'count' => $i_num * $g['price']*$discount,
							'gid' => $g['id'],
							'uid' => $uid,
							'status' => 0,
							'cate' => $cate,
							'addr' => $addr_id,
							'add_time' => time(),
							'type' => 0
						);
						if ($youhuiid) {
							$data['youhuiid'] = $youhuiid;//折扣卷id
							$data['youhui'] = $i_num * $g['price']*(1-$discount);
							$data['zhifue'] = $data['count'];
						}

						// if($yheid){
						// 	$data['youhuiid'] = 0;
						// 	$data['youhui'] = 0;
						// 	$data['zhifue'] = $data['count'];

						// 	$data['youhuiid'] = $yheid;
						// 	$data['youhui'] = $yhe;
						// 	$data['zhifue'] = $data['count'] - $yhe;
							
						// 	M('coupons')->where(array('id'=>$yheid))->save(array('status'=>1, 'usetime'=>time()));
						// }else{
						// 	$data['youhuiid'] = 0;
						// 	$data['youhui'] = 0;
						// 	$data['zhifue'] = $data['count'];
						// }

						if($order_list)
							$data['sn'] = $sn;
						
						if($fcar){
							$o_sn = $fcar;
							$res = $item_orders->where(array('id'=>$fcar))->save($data);
						}else{
							$o_sn = $item_orders->add($data);
						}
						
						if($o_sn){
							$msg = null;
							$_SESSION['order'] = array(
								'title' => $g['title'],
								'sn' => $sn,
								'count' => $g['price'] * $i_num * 100 * $discount
								);
						}else{
							$msg .= "写入数据库失败\n\r";
						}
					}
				}else{
					$msg .= "未找到该ID对应的商品\n\r";
				}
			}
			//获取支付结果
			$ref = array();
			
			if($msg){
				$ref['status'] = 0;
				$ref['message'] = $msg;
			}else{
				$ref['status'] = 1;
                $ref['sn'] = $sn;
			}
			
			echo json_encode($ref);
			exit;
		}else{
			!$id && $this->_404();

            $is_identify = M('user')->where(array('id' => $uid, 'is_identify' => 1))->count();
            if(! $is_identify) {
                // $this->error('购买前，请先完善资料~', U('User/mod'));
            }
			
			$ojl_wh = array(
				'uid'=>$uid,
				'status'=>0
			);
			$ojl = M('coupons')->where($ojl_wh)->select();
			$this->assign('ojl', $ojl);
			
			$item = $goods->where(array('id'=>$id))->find();
			if($item){
				$tmp0 = explode('|',$item['wudu']);
				$tmp1 = array();
				foreach($tmp0 as $v){
					$tmp1[] = array('wd'=>$v);
				}
				$item['wudu'] = $tmp1;
			}
			!$item && $this->_404();
			
			$last_addr = $item_orders->order('id desc')->where(array('uid'=>$uid, 'type'=>0))->find();
			$lst_addr = array('addr'=>'', 'user'=>'', 'tel'=>'');
			$lst_addr_id = 0;
			if($last_addr){
				$lst_addr_id = $last_addr['addr'];
			}
			$addr_list = $addr->where(array('uid'=>$uid))->select();
			$addr_i = 1;
			foreach($addr_list as $key => $v){
				$addr_list[$key]['i'] = $addr_i;
				if($lst_addr_id>0 && $lst_addr_id==$v['id']){
					$lst_addr['addr'] = $v['address'];
					$lst_addr['user'] = $v['user_name'];
					$lst_addr['tel'] = $v['user_tel'];
				}
				$addr_i++;
			}
			$this->assign('item', $item);
			
			$myimg = false;
			
			$f = $this->_get('f', 'trim');
			$o = $this->_get('od', 'trim');
			$num_g = $this->_get('num', 'intval');
			$o_list = M('item_orders')->where(array('id'=>$o))->find();
			if($o_list){
				$this->assign('o_num', $o_list['num']);
			}else{
				$this->assign('o_num', $num_g);
			}

			$good_type = M('item_cate')->where(array('id'=>$item['cid']))->find();

			$this->assign('good_type', $good_type['unit']);
			$this->assign('f', $f.$o);
			$this->assign('img', $myimg);
			$this->assign('addr_list', $addr_list);	//历史收件地址
			$this->assign('lst_addr', $lst_addr);	//最后一次收件地址
			$this->_config_seo(C('pin_seo_config.item'), array(
				'item_title' => $item['title'],
				'item_intro' => $item['intro'],
				'item_tag' => implode(' ', $item['tag_list']),
				'user_name' => $item['uname'],
				'seo_title' => $item['seo_title'],
				'seo_keywords' => $item['seo_keys'],
				'seo_description' => $item['seo_desc'],
			));
			$this->display();
		}
	}
	
	public function address(){
		$uid = $this->visitor->info['id'];
		$addr = M('addr');
		
		$addr_list = $addr->where(array('uid'=>$uid))->select();
		$addr_i = 1;
		foreach($addr_list as $key => $v){
			$addr_list[$key]['i'] = $addr_i;
			if($lst_addr_id>0 && $lst_addr_id==$v['id']){
				$lst_addr['addr'] = $v['address'];
				$lst_addr['user'] = $v['user_name'];
				$lst_addr['tel'] = $v['user_tel'];
			}
			$addr_i++;
		}
		$this->assign('addr_list', $addr_list);	//历史收件地址
		$this->display();
	}

    public function pay() {
        import("WxPay#Api", VENDOR_PATH . 'WxPay', '.php');
        import("WxPay#Data", VENDOR_PATH . 'WxPay', '.php');
        
        if (empty($_SESSION['current_openid'])) {
        	$openid = $this->visitor->info['openid'];	
        }else{
        	$openid = $_SESSION['current_openid'];	
        }
        

        //订单信息
        $order = session('order');
        


        //配置支付信息
        $input = new WxPayUnifiedOrder();
        $input->SetBody($order['title']);
        $input->SetAttach("test");
        $input->SetOut_trade_no($order['sn']);
        $input->SetTotal_fee($order['count']);//订单金额
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 1200));
        $input->SetGoods_tag("test");//商品标记
        $input->SetNotify_url(U('Index/orderNotify', '', false, false, true));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);

        //统一订单
        $unified = WxPayApi::unifiedOrder($input);


        //检查错误
        if(!array_key_exists("appid", $unified)
            || !array_key_exists("prepay_id", $unified)
            || $unified['prepay_id'] == "")
        {
            $this->error(array_key_exists("return_msg", $unified) ? $unified['return_msg'] : "参数错误");
        }

        $js = $this->jsPay($unified);
        $this->ajaxReturn(1, '', $js);
    }

    private function jsPay($UnifiedOrderResult)
    {
        $jsapi = new WxPayJsApiPay();
        $jsapi->SetAppid($UnifiedOrderResult["appid"]);
        $timeStamp = time();
        $jsapi->SetTimeStamp("$timeStamp");
        $jsapi->SetNonceStr(WxPayApi::getNonceStr());
        $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
        $jsapi->SetSignType("MD5");
        $jsapi->SetPaySign($jsapi->MakeSign());
        return $jsapi->GetValues();
    }

	//支付动作
	public function update_order(){
		$sn = $this->_get('sn', 'trim');
		$item_orders = M('item_orders');
		
		$data = array('status' => 1, 'support_time' => time());
		$where = array(
			'sn' => $sn,
			'status' => 0
		);
		$res = $item_orders->where($where)->save($data);
		echo "<meta charset='utf-8'>";
		echo "<script>";
		if($res){
			echo "alert('支付成功');";
			// $ref = $item_orders->where(array('sn'=>$sn))->find();
			// $dat = array(
			// 	'uid' => $ref['uid'],
			// 	'shouru' => $ref['count'],
			// 	'status' => '1',
			// 	'type' => '0',
			// 	's0time' => time(),
			// 	's1time' => time(),
			// 	's2time' => time(),
			// 	'addtime' => time()
			// );
			// $item_orders->add($dat);
		}else{
			echo "alert('更新订单状态');";
		}
		echo "location.href='index.php?m=User&a=index';";
		echo "</script>";
	}
	public function order(){
		$id = $this->_get('id', 'intval');
		$order = M('item_orders');
		$goods = M('goods');
		$addr = M('addr');
		
		$o_list = $order->where(array('id'=>$id))->find();
		if($o_list){
			$gid = $o_list['gid'];
            $a_list = $addr->where(array('id'=>$o_list['addr']))->find();

            $g_list = $goods->where(array('id'=>$gid))->select();
            //查询物流信息
			if($o_list['status'] == 2) {
                $dl = M('Deliver')->where('orderId=' . $id)->find();
                $dl && $this->assign('dl', $dl);
            }

			$o_list['add_time'] = date('Y-m-d H:i:s', $o_list['add_time']);
		}


		$_SESSION['order'] = array(
								'title' => $o_list['goods'],
								'sn' => $o_list['sn'],
								'count' => $o_list['count'] * 100
								);


		$this->assign('ord', $o_list);
		$this->assign('goo', $g_list);
		$this->assign('add', $a_list);
		$this->display();
	}
    /**
     * 点击去购买
     */
    public function tgo() {
        $url = $this->_get('to', 'base64_decode');
        redirect($url);
    }

    /**
     * AJAX获取评论列表
     */
    public function comment_list() {
        $id = $this->_get('id', 'intval');
        !$id && $this->ajaxReturn(0, L('invalid_item'));
        $item_mod = M('item');
        $item = $item_mod->where(array('id' => $id, 'status' => '1'))->count('id');
        !$item && $this->ajaxReturn(0, L('invalid_item'));
        $item_comment_mod = M('item_comment');
        $pagesize = 8;
        $map = array('item_id' => $id);
        $count = $item_comment_mod->where($map)->count('id');
        $pager = $this->_pager($count, $pagesize);
        $pager->path = 'comment_list';
        $cmt_list = $item_comment_mod->where($map)->order('id DESC')->limit($pager->firstRow . ',' . $pager->listRows)->select();
        $this->assign('cmt_list', $cmt_list);
        $data = array();
        $data['list'] = $this->fetch('comment_list');
        $data['page'] = $pager->fshow();
        $this->ajaxReturn(1, '', $data);
    }

    /**
     * 评论一个商品
     */
    public function comment() {
        foreach ($_POST as $key=>$val) {
            $_POST[$key] = Input::deleteHtmlTags($val);
        }
        $data = array();
        $data['item_id'] = $this->_post('id', 'intval');
        !$data['item_id'] && $this->ajaxReturn(0, L('invalid_item'));
        $data['info'] = $this->_post('content', 'trim');
        !$data['info'] && $this->ajaxReturn(0, L('please_input') . L('comment_content'));
        //敏感词处理
        $check_result = D('badword')->check($data['info']);
        switch ($check_result['code']) {
            case 1: //禁用。直接返回
                $this->ajaxReturn(0, L('has_badword'));
                break;
            case 3: //需要审核
                $data['status'] = 0;
                break;
        }
        $data['info'] = $check_result['content'];
        $data['uid'] = $this->visitor->info['id'];
        $data['uname'] = $this->visitor->info['username'];

        //验证商品
        $item_mod = M('item');
        $item = $item_mod->field('id,uid,uname')->where(array('id' => $data['item_id'], 'status' => '1'))->find();
        !$item && $this->ajaxReturn(0, L('invalid_item'));
        //写入评论
        $item_comment_mod = D('item_comment');
        if (false === $item_comment_mod->create($data)) {
            $this->ajaxReturn(0, $item_comment_mod->getError());
        }
        $comment_id = $item_comment_mod->add();
        if ($comment_id) {
            $this->assign('cmt_list', array(
                array(
                    'uid' => $data['uid'],
                    'uname' => $data['uname'],
                    'info' => $data['info'],
                    'add_time' => time(),
                )
            ));
            $resp = $this->fetch('comment_list');
            $this->ajaxReturn(1, L('comment_success'), $resp);
        } else {
            $this->ajaxReturn(0, L('comment_failed'));
        }
    }

    //分享商品弹窗
    public function share_item() {
        //支持的网站
        if (false === $site_list = F('item_site_list')) {
            $site_list = D('item_site')->site_cache();
        }
        $this->assign('site_list', $site_list);
        $resp = $this->fetch('dialog:share_item');
        $this->ajaxReturn(1, '', $resp);
    }

    //获取商品信息
    public function fetch_item() {
        $url = $this->_get('url', 'trim');
        $url == '' && $this->ajaxReturn(0, L('please_input') . L('correct_itemurl'));
        $aid = $this->_get('aid', 'intval');
        //获取商品信息
        $itemcollect = new itemcollect();
        !$itemcollect->url_parse($url) && $this->ajaxReturn(0, L('please_input') . L('correct_itemurl'));
        if (!$info = $itemcollect->fetch()) {
            $this->ajaxReturn(0, L('fetch_item_failed'));
        }
        $this->assign('item', $info['item']);
        $data = array();
        if ($aid) {
            $this->assign('aid', $aid);
        } else {
            //用户的专辑
            $album_list = M('album')->field('id,title')->where(array('uid' => $this->visitor->info['id']))->select();
            //专辑分类
            if (false === $album_cate_list = F('album_cate_list')) {
                $album_cate_list = D('album_cate')->cate_cache();
            }
            $this->assign('album_cate_list', $album_cate_list);
            $this->assign('album_list', $album_list);
        }
        //专辑分类
        $data['html'] = $this->fetch('dialog:fetch_item');
        $data['item'] = serialize($info['item']);
        $this->ajaxReturn(1, L('fetch_item_success'), $data);
    }

    //发布商品
    public function publish_item() {
        $item = unserialize($this->_post('item', 'trim'));
        !$item['key_id'] && $this->ajaxReturn(0, L('publish_item_failed'));
        $album_id = $this->_post('album_id', 'intval', 0);
        $ac_id = $this->_post('ac_id', 'intval', 0);
        $item['intro'] = $this->_post('intro', 'trim');
        $item['info'] = Input::deleteHtmlTags($item['info']);
        $item['uid'] = $this->visitor->info['id'];
        $item['uname'] = $this->visitor->info['username'];
        $item['status'] = C('pin_item_check') ? 0 : 1;
        //添加商品
        $item_mod = D('item');
        $result = $item_mod->publish($item, $album_id, $ac_id);
        if ($result) {
            //发布商品钩子
            $tag_arg = array('uid' => $item['uid'], 'uname' => $item['uname'], 'action' => 'pubitem');
            tag('pubitem_end', $tag_arg);
            $this->ajaxReturn(1, L('publish_item_success'));
        } else {
            $this->ajaxReturn(0, $item_mod->getError());
        }
    }

    /**
     * 喜欢一个商品
     * 返回status(todo)
     */
    public function like() {
        $id = $this->_get('id', 'intval');
        $aid = $this->_get('aid', 'intval');
        !$id && $this->ajaxReturn(0, L('invalid_item'));
        $item_mod = M('item');
        $item = $item_mod->field('id,uid,uname')->where(array('id' => $id, 'status' => '1'))->find();
        !$item && $this->ajaxReturn(0, L('invalid_item'));
        $uid = $this->visitor->info['id'];
        $uname = $this->visitor->info['username'];
        $item['uid'] == $uid && $this->ajaxReturn(0, L('like_own')); //自己的商品
        $like_mod = M('item_like');
        //是否已经喜欢过
        $is_liked = $like_mod->where(array('item_id' => $item['id'], 'uid' => $uid))->count();
        $is_liked && $this->ajaxReturn(0, L('you_was_liked'));
        if ($like_mod->add(array('item_id' => $item['id'], 'uid' => $uid, 'add_time' => time()))) {
            //增加商品喜欢数
            $item_mod->where(array('id' => $id))->setInc('likes');
            //增加用户被喜欢数
            M('user')->where(array('id' => $item['uid']))->setInc('likes');
            //增加专辑喜欢
            $aid && M('album')->where(array('id' => $aid))->setInc('likes');
            //添加喜欢钩子
            $tag_arg = array('uid' => $uid, 'uname' => $uname, 'action' => 'likeitem');
            tag('likeitem_end', $tag_arg);
            $this->ajaxReturn(1, L('like_success'));
        } else {
            $this->ajaxReturn(0, L('like_failed'));
        }
    }

    /**
     * 删除喜欢
     */
    public function unlike() {
        $id = $this->_get('id', 'intval');
        !$id && $this->ajaxReturn(0, L('invalid_item'));
        $uid = $this->visitor->info['id'];
        $like_mod = M('item_like');
        if ($like_mod->where(array('uid' => $uid, 'item_id' => $id))->delete()) {
            //喜欢数不减少~
            $this->ajaxReturn(1, L('unlike_success'));
        } else {
            $this->ajaxReturn(1, L('unlike_failed'));
        }
    }

    /**
     * 删除商品
     */
    public function delete() {
        $id = $this->_get('id', 'intval');
        $album_id = $this->_get('album_id', 'intval');
        !$id && $this->ajaxReturn(0, L('invalid_item'));
        $uid = $this->visitor->info['id'];
        $uname = $this->visitor->info['username'];
        if ($album_id) {
            //删除专辑里面的商品
            $result = M('album')->where(array('id' => $album_id, 'uid' => $uid))->count();
            if ($result) {
                M('album_item')->where(array('album_id' => $album_id, 'item_id' => $id))->delete();
                //减少专辑商品数量
                M('album')->where(array('id' => $album_id))->setDec('items');
                //刷新专辑封面
                D('album')->update_cover($album_id);
                $this->ajaxReturn(1, L('del_item_success'));
            } else {
                $this->ajaxReturn(0, L('del_item_failed'));
            }
        } else {
            $result = D('item')->where(array('id' => $id, 'uid' => $uid))->delete();
            //减少用户分享数量
            M('user')->where(array('id' => $uid))->setDec('shares');
            if ($result) {
                //添加删除钩子
                $tag_arg = array('uid' => $uid, 'uname' => $uname, 'action' => 'delitem');
                tag('delitem_end', $tag_arg);
                $this->ajaxReturn(1, L('del_item_success'));
            } else {
                $this->ajaxReturn(0, L('del_item_failed'));
            }
        }
    }


    #验证优惠码是否正确
    public function validate_discount_code(){
    	$Discount = M("discount");
    	$discount_code = $this->_get('discount_code');
    	$item = $Discount->where(array('code_num'=>$discount_code))->find();
    	if (empty($item)) {
			echo json_encode(array('code'=>-1,'message'=>'无效优惠码'));
    	}else{
    		echo json_encode(array('code'=>0,'message'=>$item['discount']));
    	}    	
    }

}